#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 基础URL
BASE_URL="http://localhost:8000/api/v1"
TOKEN=""
REFRESH_TOKEN=""

# 测试结果统计
TOTAL_TESTS=0
PASSED_TESTS=0

# 添加全局变量存储测试用户信息
TEST_USERNAME=""
TEST_PASSWORD="testpass123"

# 辅助函数
print_test_result() {
    local test_name=$1
    local result=$2
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
    
    if [ $result -eq 0 ]; then
        echo -e "${GREEN}✓ $test_name passed${NC}"
        PASSED_TESTS=$((PASSED_TESTS + 1))
    else
        echo -e "${RED}✗ $test_name failed${NC}"
    fi
}

# 1. 测试用户注册
test_user_registration() {
    echo -e "\n${YELLOW}Testing User Registration...${NC}"
    
    # 生成随机用户名以避免冲突
    local random_id=$(date +%s)
    TEST_USERNAME="testuser${random_id}"  # 保存用户名供后续测试使用
    local test_email="test${random_id}@example.com"
    
    response=$(curl -s -X POST "${BASE_URL}/user/register/" \
        -H "Content-Type: application/json" \
        -d "{
            \"username\": \"${TEST_USERNAME}\",
            \"password\": \"${TEST_PASSWORD}\",
            \"email\": \"${test_email}\",
            \"role\": \"user\"
        }")
    
    echo "Response: $response"
    if [[ $response == *'"code":200'* ]]; then
        TOKEN=$(echo "$response" | python3 -c "import sys, json; print(json.load(sys.stdin)['data']['token'])")
        REFRESH_TOKEN=$(echo "$response" | python3 -c "import sys, json; print(json.load(sys.stdin)['data']['refresh'])")
        print_test_result "User Registration" 0
    else
        print_test_result "User Registration" 1
    fi
}

# 2. 测试用户登录
test_user_login() {
    echo -e "\n${YELLOW}Testing User Login...${NC}"
    
    response=$(curl -s -X POST "${BASE_URL}/user/login/" \
        -H "Content-Type: application/json" \
        -d "{
            \"username\": \"${TEST_USERNAME}\",
            \"password\": \"${TEST_PASSWORD}\"
        }")
    
    echo "Response: $response"
    if [[ $response == *'"code":200'* ]]; then
        TOKEN=$(echo "$response" | python3 -c "import sys, json; print(json.load(sys.stdin)['data']['token'])")
        REFRESH_TOKEN=$(echo "$response" | python3 -c "import sys, json; print(json.load(sys.stdin)['data']['refresh'])")
        print_test_result "User Login" 0
    else
        print_test_result "User Login" 1
    fi
}

# 3. 测试获取用户信息
test_get_user_info() {
    echo -e "\n${YELLOW}Testing Get User Info...${NC}"
    
    response=$(curl -s -X GET "${BASE_URL}/user/info/" \
        -H "Authorization: Bearer ${TOKEN}")
    
    echo "Response: $response"
    if [[ $response == *'"code":200'* ]]; then
        print_test_result "Get User Info" 0
    else
        print_test_result "Get User Info" 1
    fi
}

# 4. 测试修改密码
test_change_password() {
    echo -e "\n${YELLOW}Testing Change Password...${NC}"
    
    response=$(curl -s -X PUT "${BASE_URL}/user/password/" \
        -H "Authorization: Bearer ${TOKEN}" \
        -H "Content-Type: application/json" \
        -d "{
            \"oldPassword\": \"${TEST_PASSWORD}\",
            \"newPassword\": \"newtestpass123\"
        }")
    
    echo "Response: $response"
    if [[ $response == *'"code":200'* ]]; then
        TEST_PASSWORD="newtestpass123"  # 更新密码
        print_test_result "Change Password" 0
    else
        print_test_result "Change Password" 1
    fi
}

# 5. 测试修改邮箱
test_change_email() {
    echo -e "\n${YELLOW}Testing Change Email...${NC}"
    
    # 生成随机邮箱以避免冲突
    local random_id=$(date +%s)
    local new_email="newemail${random_id}@example.com"
    
    response=$(curl -s -X PUT "${BASE_URL}/user/email/" \
        -H "Authorization: Bearer ${TOKEN}" \
        -H "Content-Type: application/json" \
        -d "{
            \"email\": \"${new_email}\"
        }")
    
    echo "Response: $response"
    if [[ $response == *'"code":200'* ]]; then
        print_test_result "Change Email" 0
    else
        print_test_result "Change Email" 1
    fi
}

# 6. 测试无效登录
test_invalid_login() {
    echo -e "\n${YELLOW}Testing Invalid Login...${NC}"
    
    response=$(curl -s -X POST "${BASE_URL}/user/login/" \
        -H "Content-Type: application/json" \
        -d '{
            "username": "nonexistent",
            "password": "wrongpass"
        }')
    
    echo "Response: $response"
    if [[ $response == *'"code":401'* ]]; then
        print_test_result "Invalid Login" 0
    else
        print_test_result "Invalid Login" 1
    fi
}

# 7. 测试未授权访问
test_unauthorized_access() {
    echo -e "\n${YELLOW}Testing Unauthorized Access...${NC}"
    
    response=$(curl -s -X GET "${BASE_URL}/user/info/")
    
    echo "Response: $response"
    if [[ $response == *'"detail":"身份认证信息未提供。"'* ]]; then
        print_test_result "Unauthorized Access" 0
    else
        print_test_result "Unauthorized Access" 1
    fi
}

# 8. 测试用户注销
test_user_logout() {
    echo -e "\n${YELLOW}Testing User Logout...${NC}"
    
    if [ -z "$REFRESH_TOKEN" ]; then
        echo "No refresh token available"
        print_test_result "User Logout" 1
        return
    fi
    
    response=$(curl -s -X POST "${BASE_URL}/user/logout/" \
        -H "Authorization: Bearer ${TOKEN}" \
        -H "Content-Type: application/json" \
        -d "{\"refresh_token\": \"${REFRESH_TOKEN}\"}")
    
    echo "Response: $response"
    if [[ $response == *'"code":200'* ]]; then
        print_test_result "User Logout" 0
    else
        print_test_result "User Logout" 1
    fi
}

# 运行所有测试
run_all_tests() {
    echo -e "${YELLOW}Starting API Tests...${NC}"
    
    test_user_registration
    test_user_login
    test_get_user_info
    test_change_password
    test_change_email
    test_invalid_login
    test_unauthorized_access
    test_user_logout
    
    echo -e "\n${YELLOW}Test Results:${NC}"
    echo -e "Total Tests: $TOTAL_TESTS"
    echo -e "Passed: ${GREEN}$PASSED_TESTS${NC}"
    echo -e "Failed: ${RED}$((TOTAL_TESTS - PASSED_TESTS))${NC}"
}

# 执行测试
run_all_tests